#!/usr/bin/env python 
# -*- coding:utf-8 -*-

# coding:utf-8
# 运行前请先做以下工作：
# pip install lxml
# 将所有的图片及xml文件存放到xml_dir指定的文件夹下，并将此文件夹放置到当前目录下
#

import os
import glob
import json
import shutil
import numpy as np
import xml.etree.ElementTree as ET
import cv2
from tqdm import tqdm

START_BOUNDING_BOX_ID = 1

xml_dir = "data/side/train/box/"
jpg_dir = "data/side/train/image"

savepath="data/side/train/halfimage/"

if not os.path.exists(savepath):
    os.makedirs(savepath)


def border_confirm(height, width, xmin, xmax, ymin, ymax):
    xmax = width - 1 if xmax > width - 1 else xmax
    ymax = height - 1 if ymax > height - 1 else ymax
    xmin = xmax - 1 if xmin >= xmax else xmin
    ymin = ymax - 1 if ymin >= ymax else ymin
    return xmin, xmax, ymin, ymax


def get(root, name):
    return root.findall(name)


def get_and_check(root, name, length):
    vars = get(root, name)
    if len(vars) == 0:
        raise NotImplementedError('Can not find %s in %s.' % (name, root.tag))
    if length and len(vars) != length:
        raise NotImplementedError('The size of %s is supposed to be %d, but is %d.' % (name, length, len(vars)))
    if length == 1:
        vars = vars[0]
    return vars


def convert(xml_list, json_file):
    json_dict = {"images": [], "type": "instances", "annotations": [], "categories": []}
    categories = pre_define_categories.copy()
    bnd_id = START_BOUNDING_BOX_ID
    all_categories = {}

    for index, line in enumerate(tqdm(list(xml_list))):
        xml_f = line
        tree = ET.parse(xml_f)  # 打开xml文件
        root = tree.getroot()  # 获取根节点\

        filename = os.path.basename(xml_f)[:-4] + ".jpg"

        # if filename not in train_list:
        # if filename not in val_list:
        #     continue

        # basename函数返回不带路径的文件名 ,如'/Users/beazley/Data/data.csv' 返回‘data.csv’
        filenamel = os.path.basename(xml_f)[:-4] + "l.jpg"
        filenamer = os.path.basename(xml_f)[:-4] + "r.jpg"

        image_idl = index
        image_idr = 1500+index

        # xml文件中没有size属性，所以采用读取图片获取
        # size = get_and_check(root, 'size', 1)
        # width = int(get_and_check(size, 'width', 1).text)
        # height = int(get_and_check(size, 'height', 1).text)

        img_name = os.path.join(jpg_dir, filename)

        img = cv2.imread(img_name)
        height, width, _ = img.shape
        imgl = img[:, :width // 2]
        imgr = img[:, width // 2:]
        imgnamel = os.path.join(savepath, filenamel)
        imgnamer = os.path.join(savepath, filenamer)
        cv2.imwrite(imgnamel, imgl)
        cv2.imwrite(imgnamer, imgr)
        height, width, _ = img.shape

        for obj in get(root, 'object'):
            category = get_and_check(obj, 'name', 1).text
            if category in all_categories:
                all_categories[category] += 1
            else:
                all_categories[category] = 1
            if category not in categories:
                if only_care_pre_define_categories:
                    continue
                new_id = len(categories) + 1
                print(
                    "[warning] category '{}' not in 'pre_define_categories'({}), create new id: {} automatically".format(
                        category, pre_define_categories, new_id))
                categories[category] = new_id

            category_id = categories[category]
            bndbox = get_and_check(obj, 'bndbox', 1)
            xmin = int(float(get_and_check(bndbox, 'xmin', 1).text))
            ymin = int(float(get_and_check(bndbox, 'ymin', 1).text))
            xmax = int(float(get_and_check(bndbox, 'xmax', 1).text))
            ymax = int(float(get_and_check(bndbox, 'ymax', 1).text))

            xmin, xmax, ymin, ymax = border_confirm(height, width, xmin, xmax, ymin, ymax)
            assert (xmax > xmin), "xmax <= xmin, {}".format(line)
            assert (ymax > ymin), "ymax <= ymin, {}".format(line)

            if xmin>=width//2:
                image = {'file_name': filenamer, 'height': height, 'width': width-width//2, 'id': image_idr}
                o_width = abs(xmax - xmin)
                o_height = abs(ymax - ymin)
                ann = {'area': o_width * o_height, 'iscrowd': 0, 'image_id':
                    image_idr, 'bbox': [xmin-width//2, ymin, o_width, o_height],
                       'category_id': category_id, 'id': bnd_id, 'ignore': 0,
                       'segmentation': []}
            else:
                image = {'file_name': filenamel, 'height': height, 'width': width//2, 'id': image_idl}
                o_width = abs(xmax - xmin)
                o_height = abs(ymax - ymin)
                ann = {'area': o_width * o_height, 'iscrowd': 0, 'image_id':
                    image_idl, 'bbox': [xmin, ymin, o_width, o_height],
                       'category_id': category_id, 'id': bnd_id, 'ignore': 0,
                       'segmentation': []}

            json_dict['images'].append(image)
            json_dict['annotations'].append(ann)

            bnd_id = bnd_id + 1

    for cate, cid in categories.items():
        cat = {'supercategory': 'target', 'id': cid, 'name': cate}
        json_dict['categories'].append(cat)
    json_fp = open(json_file, 'w')
    json_str = json.dumps(json_dict)
    json_fp.write(json_str)
    json_fp.close()
    print("------------create {} done--------------".format(json_file))
    print("find {} categories: {} -->>> your pre_define_categories {}: {}".format(len(all_categories),
                                                                                  all_categories.keys(),
                                                                                  len(pre_define_categories),
                                                                                  pre_define_categories.keys()))
    print("category: id --> {}".format(categories))
    print(categories.keys())
    print(categories.values())


if __name__ == '__main__':

    classes = ['目标物']
    pre_define_categories = {}
    for i, cls in enumerate(classes):
        pre_define_categories[cls] = i + 1

    only_care_pre_define_categories = True  # or False

    save_json_train = 'data/annotations/side_half_train.json'

    xml_list = glob.glob(xml_dir + "/*.xml")
    xml_list = np.sort(xml_list)

    # 打乱数据集
    np.random.seed(100)
    np.random.shuffle(xml_list)

    # 按比例划分打乱后的数据集
    train_ratio = 1.0
    val_ratio = 0
    train_num = int(len(xml_list) * train_ratio)
    # val_num = int(len(xml_list) * val_ratio)
    xml_list_train = xml_list[:train_num]
    # xml_list_val = xml_list[train_num: train_num + val_num]
    # xml_list_test = xml_list[train_num + val_num:]

    # 将xml文件转为coco文件，在指定目录下生成三个json文件（train/test/food）
    convert(xml_list_train, save_json_train)
    # convert(xml_list_val, save_json_val)
    # convert(xml_list_test, save_json_test)

    print("-" * 50)
    print("train number:", len(xml_list_train))
    # print("val number:", len(xml_list_val))
    # print("test number:", len(xml_list_val))
